import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';

///安全措施选择弹窗
///[text] 传入的字段
///[onCallback] 完成回调
class MeasureDynamicSelect extends StatefulWidget {
  const MeasureDynamicSelect({required this.text, required this.onCallback, super.key});

  final String text;
  final Function(String) onCallback;

  @override
  State<MeasureDynamicSelect> createState() => _MeasureDynamicSelectState();
}

class _MeasureDynamicSelectState extends State<MeasureDynamicSelect> {
  late String title; // 需要选择的标题
  List<String> selectContentList = []; // 选择列表
  List<String> selectList = []; // 是否选择选择字段

  @override
  void initState() {
    super.initState();
    // 查找第一个"-<"的索引
    final int startIndex = widget.text.indexOf('-<');
    // 截取从字符串开头到第一个"-<"之前的部分
    title = widget.text.substring(0, startIndex);
    // 查询字符中的'-<'和'+>'之间显示的字段
    final matches = RegExp(r'-<([^>]+)>-').allMatches(widget.text);
    // 选择字段
    selectList = widget.text.split(RegExp(r'-<([^>]+)>-'));
    selectList.removeAt(0);
    // 遍历初始化数据
    for (int index = 0; index < matches.length; index++) {
      final String initialValue = matches.elementAt(index).group(1) ?? '';
      selectContentList.add(initialValue);
    }
  }

  /// 获取修改后的数据
  String getUpdatedText() {
    // final List<String> parts = widget.text.split(RegExp(r'-<([^>]+)>-'));
    selectList.insert(0, title);
    final StringBuffer updatedText = StringBuffer();

    for (int i = 0; i < selectList.length; i++) {
      updatedText.write(selectList[i]);
      if (i < selectContentList.length) {
        updatedText.write('-<');
        updatedText.write(selectContentList[i]);
        updatedText.write('>-');
      }
    }
    return updatedText.toString();
  }

  /// 替换第n个字符
  ///[input] 显示的字段
  ///[target] 查找的字符
  ///[replacement] 替换的字段
  ///[n] 出现的索引
  String replaceNthOccurrence(String input, String target, String replacement, int n) {
    int count = 0;
    String result = input;

    final RegExp regex = RegExp(target);

    result = result.replaceFirstMapped(regex, (match) {
      count++;
      if (count == n) {
        return replacement;
      } else {
        return match.group(0).toString(); // 不替换，保持原样
      }
    });

    return result;
  }

  /// 字符是否存在
  bool doesTheCharacterExist(String input, String target, int n) {
    return findNthIndexOf(input, target, n) != -1;
  }

  /// 查询第n个字符所在位置
  ///[input] 显示的字段
  ///[target] 查找的字符
  int findNthIndexOf(String input, String target, int n) {
    int index = input.indexOf(target);
    int count = 0;

    while (index != -1 && count < n) {
      index = input.indexOf(target, index + 1);
      count++;
    }
    return index;
  }

  /// 显示的按钮样式
  Widget _getButtonStyle(String field) {
    return field.contains('-~')
        ? SvgPicture.asset(
            AppImages.icon_un_select,
            height: 16.w,
            width: 16.w,
          )
        : SvgPicture.asset(
            AppImages.icon_select,
            height: 16.w,
            width: 16.w,
          );
  }

  /// 获取选择项
  Widget _getSelectView() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(title),
        AppGaps.vGap10,
        ListView.separated(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemCount: selectContentList.length,
          itemBuilder: (context, index) {
            return Row(
              children: [
                _getButtonStyle(selectList[index]),
                Expanded(child: Text(selectContentList[index])),
              ],
            ).clickOnce(() {
              // 点击选中或取消
              // '-~'为未选中，'+~'为选中
              if (selectList[index].contains('-~')) {
                selectList[index] = selectList[index].replaceAll('-~', '+~');
              } else {
                selectList[index] = selectList[index].replaceAll('+~', '-~');
              }
              setState(() {});
            });
          },
          separatorBuilder: (BuildContext context, int index) {
            return AppGaps.vGap10;
          },
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: Container(
        width: 300.w,
        height: 250.w,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(20.w)),
          gradient: const LinearGradient(
              //渐变位置
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              //渐变颜色[始点颜色, 结束颜色]
              colors: [
                Color(0xffE7EAFF),
                Color(0xffffffff),
                Color(0xffffffff),
                Color(0xffffffff),
              ]),
        ),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Container(
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    AppGaps.vGap20,
                    Expanded(
                        child: Container(
                      alignment: Alignment.topLeft,
                      decoration: BoxDecoration(
                        color: const Color(0xffF7F7FB),
                        borderRadius: BorderRadius.all(Radius.circular(20.w)),
                      ),
                      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.w),
                      child: SingleChildScrollView(
                        child: _getSelectView(),
                      ),
                    )),
                    AppGaps.vGap20,
                    SizedBox(
                      width: 270.w,
                      height: 40.w,
                      child: ElevatedButton(
                        style: ButtonStyle(
                          backgroundColor: MaterialStateProperty.all(const Color(0xff5C6DFF)),
                        ),
                        child: Text(
                          '确定',
                          style: TextStyle(fontSize: 16.sp, color: Colors.white),
                        ),
                        onPressed: () {
                          widget.onCallback(getUpdatedText());
                          Get.back();
                        },
                      ),
                    ),
                    AppGaps.vGap10,
                  ],
                )),
            Positioned(
                top: 4.w,
                right: 4.w,
                child: IconButton(
                  icon: Container(
                    width: 30.w,
                    height: 30.w,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(15.w)),
                    ),
                    child: Icon(
                      Icons.close,
                      color: Colors.grey,
                      size: 21.w,
                    ),
                  ),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                ))
          ],
        ),
      ),
    );
  }
}
